package models

import (
	"gorm.io/gorm"
)

type News struct {
	gorm.Model
	UserId  int    `gorm:"type:int" json:"userId"`
	Title   string `gorm:"type:varchar(100)" json:"title"`
	Content string `gorm:"type:text" json:"content"`
	TypeID  int    `gorm:"type:int" json:"typeID"`
	Cover   string `gorm:"type:varchar(225)" json:"cover"`
	Remark  string `gorm:"type:varchar(225)" json:"remark"`
}

type NewsType struct {
	gorm.Model
	Name string `gorm:"type:varchar(100);not null;index;comment:'名称'"`
}

func (u *News) Create() error {
	return DB.Create(&u).Error
}
func (u *News) List(keyword string, typeId, page, pageSize int) (newsList []*News, err error) {
	db := DB.Where("title like ?", "%"+keyword+"%")
	if typeId > 0 {
		db = db.Where("type_id=?", typeId)
	}
	err = db.Scopes(Paginate(page, pageSize)).Find(&newsList).Error
	return
}
func Paginate(page, pageSize int) func(db *gorm.DB) *gorm.DB {
	return func(db *gorm.DB) *gorm.DB {

		if page <= 0 {
			page = 1
		}

		switch {
		case pageSize > 100:
			pageSize = 100
		case pageSize <= 0:
			pageSize = 10
		}

		offset := (page - 1) * pageSize
		return db.Offset(offset).Limit(pageSize)
	}
}
